package com.xizimall.order.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.mysql.fabric.xmlrpc.base.Data;
import com.xizimall.mapper.TbOrderItemMapper;
import com.xizimall.mapper.TbOrderMapper;
import com.xizimall.mapper.TbOrderShippingMapper;
import com.xizimall.order.dao.JedisClient;
import com.xizimall.order.service.OrderService;
import com.xizimall.pojo.TbOrder;
import com.xizimall.pojo.TbOrderItem;
import com.xizimall.pojo.TbOrderShipping;
import com.xizimall.common.pojo.XizimallResult;
/**
 * 生成订单服务
 * <p>Title: OrderServiceImpl</p>
 * <p>Description: </p>
 * <p>华南理工大学研究生</p> 
 * @author	李隆熹
 * @date	2018年5月2日下午3:27:58
 * @version 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private TbOrderMapper orderMapper;
    
    @Autowired
    private TbOrderItemMapper orderItemMapper;
    
    @Autowired
    private TbOrderShippingMapper orderShippingMapper;
    
    @Autowired
    private JedisClient jedisClient;
    
    @Value("${ORDER_GEN_KEY}")
    private String ORDER_GEN_KEY;
    
    @Value("${ORDER_INIT_ID}")
    private String ORDER_INIT_ID;
    
    @Value("${ORDER_DETAIL_GEN_KEY}")
    private String ORDER_DETAIL_GEN_KEY;
	@Override
	public XizimallResult createOrder(TbOrder order, List<TbOrderItem> itemList, TbOrderShipping orderShipping) {
		//向订单插入记录
		//获得订单号
		String string = jedisClient.get(ORDER_GEN_KEY);
		if(StringUtils.isBlank(string)){
			jedisClient.set(ORDER_GEN_KEY, ORDER_INIT_ID);
		}
		Long orderId = jedisClient.incr(ORDER_GEN_KEY);
		//补全pojo属性
		order.setOrderId(orderId+"");
		//状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
		order.setStatus(1);
		Date date = new Date();
		order.setCreateTime(date);
		order.setUpdateTime(date);
		//0:未评价 1:已评价
		order.setBuyerRate(0);
		//向订单列表插入数据
		orderMapper.insert(order);
		//插入订单明细
		for(TbOrderItem tbOrderItem:itemList){
			//补全订单明细
			//获取订单明细id
			Long orderDetailId = jedisClient.incr(ORDER_DETAIL_GEN_KEY);
			tbOrderItem.setId(orderDetailId+"");
			tbOrderItem.setOrderId(orderId+"");
			//向订单明细中插入记录
			orderItemMapper.insert(tbOrderItem);
		}
		//插入物流表
		//补全物流表信息
		orderShipping.setOrderId(orderId+"");
		orderShipping.setCreated(date);
		orderShipping.setUpdated(date);
		orderShippingMapper.insert(orderShipping);
		return XizimallResult.ok(orderId);
	}

}
